package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.JobRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Slf4j
@Setter
@Getter
@Component
public class InitSeckillProductJob implements SimpleJob {

    @Value("${jobCron.initSeckillProduct}")
    private String cron;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SeckillProductFeignApi seckillProductFeignApi;

    @Override
    public void execute(ShardingContext shardingContext) {
        List<Integer> timeList = Arrays.asList(10, 12, 14);
        for (Integer time : timeList) {
            doWork(time);
        }
    }

    public void doWork(Integer time) {
        Result<List<SeckillProductVo>> result = seckillProductFeignApi.queryByTime(time);
        if (result.hasError()) {
            log.warn("[初始化秒杀商品服务]: 未查到今天的秒杀商品信息, {}", JSON.toJSONString(result));
            return;
        }

        List<SeckillProductVo> productVoList = result.getData();
        log.info("[初始化秒杀商品服务]: 参与秒伤的场次{}, {}件商品参与秒杀活动", time, productVoList.size());
        // 将参与秒杀商品信息存入redis缓存
        for (SeckillProductVo vo : productVoList) {
            // 存入 Hash 结构
            redisTemplate.opsForHash().put(JobRedisKey.INIT_SECKILL_PROFUCT_DETAILS_HASH.getRealKey(time.toString()), vo.getId().toString(), JSON.toJSONString(vo));
            // 提前将库存预存入 redis
            redisTemplate.opsForHash().put(JobRedisKey.INIT_SECKILL_PROFUCT_DETAILS_HASH.getRealKey(time.toString()), vo.getId() + ":stockCount", vo.getStockCount().toString());
        }
        redisTemplate.opsForValue().set(JobRedisKey.INIT_SECKILL_PROFUCT_LIST_STRING.getRealKey(time.toString()), JSON.toJSONString(productVoList));
        log.info("[初始化秒杀商品服务]: 准备开始初始化数据已完成~~~~~");
    }
}